<?php

class GenerateController extends Controller {
    public function init() {
        if (Yii::app()->user->isGuest) {
            $this->redirect('/site/login');
        }
    }

    public function actionIndex() {
        $model = new MemeForm();
        $remixMeme = null;

        $memeData = array();
        
        if(isset($_POST['MemeForm'])) {
            $memeData = $_POST['MemeForm'];
            $model->attributes = $_POST['MemeForm'];
        }
        
        if((isset($_POST['MemeForm']) && $model->validate()) || ($memeData = Meme::popMemeFromSession())) {
            $remixMemeId = Yii::app()->request->getParam('meme', 0);
            if($remixMemeId) {
                $remixMeme = Meme::model()->findByPk($remixMemeId);
            }
            if($remixMeme && !is_file($remixMeme->absolute_path)) {
                $remixMeme = null;
            }
            $tmpPath = dirname(__FILE__) . '/../../tmp/';
            // save the meme image
            if(substr($memeData['image'], -4) != '.png' && substr($memeData['image'], -4) != '.gif') {
                $name = uniqid();
                $file = Utility::beginsWith($memeData['image'], 'data:image/png;base64,') ? "$name.png" :  "$name.gif";
                $data = str_replace('data:image/png;base64,', '', $memeData['image']);
                $data = base64_decode($data);
                
                imagepng(imagecreatefromstring($data), $tmpPath . $file);
                $memeData['image'] = $tmpPath . $file;
            }
            
            if(!Yii::app()->user->isGuest) {
                $name = uniqid();
                
                $meme = new Meme();
                $meme->attributes = $memeData;
                $meme->file = basename($memeData['image']);
                $meme->user_fk = Yii::app()->user->id;
                $meme->remix_id = $remixMemeId;
                /* auto published and active */
                $meme->is_published = isset($_POST['MemeForm']['publish']) ? $_POST['MemeForm']['publish'] : 1;
                $meme->is_active = 1;
                /* end auto published and active */

                $file = $meme->absolute_path;
                $file2 = $meme->absolute_path_orignal;
                $file_thumb = $meme->absolute_path_thumb;
                
                if($meme->validate()) {
                    $data = str_replace('data:image/png;base64,', '', $memeData['image']);
                    $data = base64_decode($data);
                    $e = new CEvent($this);
                    $im = (substr($memeData['image'], -4) == '.gif') ? imagecreatefromgif($memeData['image']) : imagecreatefrompng($memeData['image']);
                    $e->params['meme_image'] = $im;
                    Yii::app()->plugin->onMemeImage($e);
                    
                    imagepng($e->params['meme_image'], $file);
                    rename($memeData['image'], $file2);
                    
                    $meme->generateThumb();
                    $meme->putWatermark();
                    
                    
                    $meme->save();
                    Utility::setFlash(Yii::t('yii', 'Your meme will be avialable once approved!'), 'success');
                    Yii::app()->request->redirect(array('/site/index'));
                }
            }
        }
        
        $this->render('index', array(
            'remixMeme' => $remixMeme,
            'model' => $model,
        ));
    }
    

    public function actionUpload_bg() {
        $ext = strtolower(substr($_FILES['files']['name'][0], -3));
        if(!in_array($ext, array(
            'jpg',
            'gif',
            'png',
        ))) {
            echo json_encode(array(
                    'message' => Yii::t('yii', 'Invalid File'),
                    'error' => 1,
            ));
            Yii::app()->end();
        }
        
        $upload_handler = new UploadHandler(array(
            'file_name' => uniqid(),
            'upload_dir' => Yii::getPathOfAlias('webroot.' . Yii::app()->params['upload_dir']) . DIRECTORY_SEPARATOR,
            'upload_url' => Yii::app()->createAbsoluteUrl(Yii::app()->params['upload_dir']) . '/',
            'image_versions' => array(
                '' => array(
                    'max_width' => 450,
                    'max_height' => 450,
                    'jpeg_quality' => 100
                ),
                'medium' => array(
                    'max_width' => 150,
                    'max_height' => 150,
                    'jpeg_quality' => 100
                ),
                'thumbnail' => array(
                    // Uncomment the following to force the max
                    // dimensions and e.g. create square thumbnails:
                    //'crop' => true,
                    'max_width' => 80,
                    'max_height' => 80
                )
            ),
        ));
    }

}